import router, { asyncRouter } from './router'
// 虚拟进度条 nprogress的 vue 使用场景
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
// 导入store
import store from '@/store'
// 登录白名单 登录 注册 404
const whiteList = ['/login']
// 前置路由守卫
router.beforeEach(async(to, from, next) => {
  NProgress.start()
  next()
  if (store.state.user.token) {
    if (whiteList.includes(to.path)) {
      next('/')
      NProgress.done()
    } else {
      // 在这里触发vuex发送用户基本信息ajax
      if (!store.state.user.userInfo.userId) {
        const res = await store.dispatch('user/getUserInforAction')
        // console.log('测试', res)
        const { menus } = res.roles
        // console.log(1, menus)
        const filterRouters = asyncRouter.filter(item => {
          // console.log(2, item)
          return menus.includes(item.children[0].name)
        })
        // console.log(3, filterRouters)
        filterRouters.push({ path: '*', redirect: '/404', hidden: true })
        // 为了侧边栏,菜单的动态展示,要将vuex将所有的存储
        store.commit('user/setRoutes', filterRouters)
        // 这里要添加动态路由
        router.addRoutes(filterRouters)
      }
      next()
    }
  } else {
    //
    if (whiteList.includes(to.path)) {
      next()
    } else {
      next('/login')
      NProgress.done()
    }
  }
})
// 后置路由守卫
router.afterEach(() => {
  NProgress.done()
})
